package cn.edu.zstu.qingzhu.qingzhushop.controller;

import cn.edu.zstu.qingzhu.qingzhushop.common.Constants;
import cn.edu.zstu.qingzhu.qingzhushop.entity.LoginDTO;
import cn.edu.zstu.qingzhu.qingzhushop.entity.RegisterDTO;
import cn.edu.zstu.qingzhu.qingzhushop.entity.ResponseBean;
import cn.edu.zstu.qingzhu.qingzhushop.entity.User;
import cn.edu.zstu.qingzhu.qingzhushop.service.IUserService;
import cn.edu.zstu.qingzhu.qingzhushop.util.VerificationCode;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @Author ShenTuZhiGang
 * @Version 1.0.0
 * @Date 2020-07-21 15:23
 */
@Controller
@Api(tags = "根接口")
public class IndexController {

    @Autowired
    IUserService iUserService;
    @Autowired
    @Qualifier("defaultKaptcha")
    private DefaultKaptcha kaptchaProducer;
    @Autowired
    @Qualifier("shopKaptcha")
    private DefaultKaptcha shopKaptchaProducer;

    @RequestMapping(value = "/",method = {RequestMethod.GET})
    public String root (){
        return "index";
    }

    @RequestMapping(value = "/verifyCode",method = {RequestMethod.GET})
    public void verifyCode(HttpSession session, HttpServletResponse resp) throws IOException {
        VerificationCode code = new VerificationCode();
        BufferedImage image = code.getImage();
        String text = code.getText();
        session.setAttribute("verify_code", text);
        VerificationCode.output(image,resp.getOutputStream());
    }


    @RequestMapping(value = "/login1",method = { RequestMethod.GET})
    public Object login1(Authentication authentication){
        if(authentication==null){
            return "index";
        }else {
            return "redirect:/";
        }

    }
    @RequestMapping(value = "/login",method = { RequestMethod.GET})
    public ResponseBean login(LoginDTO dto){
        if (StringUtils.isEmpty(dto.getPassword()) || StringUtils.isEmpty(dto.getPhone())) {
            return new ResponseBean.Builder()
                    .setStatus(400)
                    .setMsg("必填项未填！")
                    .setData(null)
                    .build();
        }
        //User user = iUserService.registerUser(dto.getPhone(),dto.getPassword());
        return ResponseBean.success("登录成功");

    }
    @RequestMapping(value ="/register",method = { RequestMethod.POST})
    public Object register(RegisterDTO registerDTO) {
        if (StringUtils.isEmpty(registerDTO.getPassword()) || StringUtils.isEmpty(registerDTO.getPhone())) {
            return new ResponseBean.Builder()
                    .setStatus(400)
                    .setMsg("必填项未填！")
                    .setData(null)
                    .build();
        }
        User user = iUserService.registerUser(registerDTO.getPhone(),registerDTO.getPassword());
        return ResponseBean.success(user);
    }

    @RequestMapping(value = "/logout1",method = { RequestMethod.GET})
    public Object logout(Authentication authentication){
        authentication.setAuthenticated(false);
        if(authentication==null){
            return "index";
        }else {
            return "redirect:/";
        }

    }



    @GetMapping("/kaptcha")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String verifyCode = kaptchaProducer.createText();
            httpServletRequest.getSession().setAttribute("verifyCode", verifyCode);
            BufferedImage challenge = kaptchaProducer.createImage(verifyCode);
            ImageIO.write(challenge, "jpg", imgOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        writeToResponse(httpServletResponse,imgOutputStream);
    }

    @GetMapping("/shop/kaptcha")
    public void mallKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String verifyCode = shopKaptchaProducer.createText();
            httpServletRequest.getSession().setAttribute(Constants.MALL_VERIFY_CODE_KEY, verifyCode);
            BufferedImage challenge = shopKaptchaProducer.createImage(verifyCode);
            ImageIO.write(challenge, "jpg", imgOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        writeToResponse(httpServletResponse,imgOutputStream);
    }
    private void writeToResponse(HttpServletResponse httpServletResponse,ByteArrayOutputStream imgOutputStream) throws Exception{
        byte[] captchaOutputStream = null;
        captchaOutputStream = imgOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaOutputStream);
        responseOutputStream.flush();
        responseOutputStream.close();
    }
}
